package com.ysu.zyw.service;

import com.ysu.zyw.dao.BlogUserMapper;
import com.ysu.zyw.modal.dto.BlogRegisterInformation;
import com.ysu.zyw.modal.po.BlogUserEntity;
import com.ysu.zyw.other.exception.KnownException;
import com.ysu.zyw.other.security.BcryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by zhang_yao_wu1993 on 15/4/25.
 *
 * @author by Zerur
 */
@Service("blogUserService")
public class BlogUserService {
    private BlogUserMapper blogUserMapper;

    public BlogUserMapper getBlogUserMapper() {
        return blogUserMapper;
    }

    @SuppressWarnings("all")
    @Resource
    public void setBlogUserMapper(BlogUserMapper blogUserMapper) {
        this.blogUserMapper = blogUserMapper;
    }


    @Transactional
    public void register(BlogRegisterInformation blogRegisterInformation) {
        // 是否合法
        if(!blogRegisterInformation.getPassword().equals(blogRegisterInformation.getPassword_confirm())) {
            throw new KnownException("两次输入的密码不一致");
        }

        // 是否id可以注册
        Integer sameUsernameUserCount = blogUserMapper.selectBlogUserEntityCountByUsername(blogRegisterInformation.getUsername());
        if(sameUsernameUserCount != 0) {
            throw  new KnownException("用户名已经被使用");
        }

        // 加密
        BlogUserEntity blogUserEntity = new BlogUserEntity(blogRegisterInformation);
        BcryptPasswordEncoder.encode(blogUserEntity);

        // 注册
        blogUserMapper.insertBlogUserEntity(blogUserEntity);
    }
}
